#!/bin/bash

# 项目目录
PROJECT_DIR=$(pwd)

# 服务名称
SERVICE_NAME="text-sync"

# 停止服务（如果已存在）
sudo systemctl stop $SERVICE_NAME 2>/dev/null

# 创建 systemd 服务文件
SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service"

# 创建 manage-certificates.js 脚本
node manage-certificates.js 1

# 创建 systemd 服务文件内容
SERVICE_CONTENT="[Unit]
Description=Text Sync Service
After=network.target

[Service]
ExecStart=/usr/bin/node $PROJECT_DIR/server.js
WorkingDirectory=$PROJECT_DIR
Restart=always
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=$SERVICE_NAME

[Install]
WantedBy=multi-user.target"

# 写入 systemd 服务文件
echo "$SERVICE_CONTENT" | sudo tee $SERVICE_FILE

# 重新加载 systemd
sudo systemctl daemon-reload

# 启动服务
sudo systemctl start $SERVICE_NAME

# 启用服务开机启动
sudo systemctl enable $SERVICE_NAME

echo "Service $SERVICE_NAME installed and started successfully."
